<template>
  <div class="page-wrapper">
    <Form ref="formHead" :model="pageData" :rules="rulePageData">
    <div class="head-part"> 
      <div class="orderNo" v-if="pageData.orderNo"><div class="label">采购单:</div><div>{{pageData.orderNo}}</div></div>
      <div class="des-content">
        <div class="left-part">
          <FormItem label="供应商:" prop="supplierId" :label-width="70">
            <Select :disabled="reviewMode" v-model="pageData.supplierId" class='none' filterable>
                <Option v-for="item in supplierList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem v-if="pageData.supplierId" label="供应商联系人:" :label-width="120">
            <div>{{supplierLinkName}}</div>
          </FormItem>
          <FormItem v-if="pageData.supplierId" label="联系电话:" :label-width="80">
            <div>{{supplierLinkNumber}}</div>
          </FormItem>
        </div>
        <div class="right-part">
          <FormItem label="采购日期:" prop="createTime" :label-width="80">
            <DatePicker :disabled="reviewMode" :readonly="reviewMode" v-model="pageData.createTime" type="datetime" class='ntwo' />
          </FormItem>
          <FormItem label="采购人:" :label-width="80">
            <div v-if="mode === 'add'">{{username}}</div>
            <div v-else>{{pageData.createUserName}}</div>
          </FormItem>
        </div>
        <Button type="primary" class='nthree' v-if="!reviewMode" @click="showDrugPurchaseModal = true;">添加药品</Button>
      </div>
    </div>
    <div class="table-part">
      <div class="medical-block" v-for="item in displayDrugGroup">
        <div class="head">
          <div class="left-part">
            <div class="item">
              <div class="label">药品通用名：</div><div class="label">{{item.ypmc}}</div>
            </div>
            <div class="item">
              <div class="label">剂型：</div><div class="label">{{item.ypjx}}</div>
            </div>
            <div class="item">
              <div class="label">规格：</div><div class="label">{{item.ypgg}}</div>
            </div>
            <div class="item">
              <div class="label">厂家：</div><div class="label">{{item.scqymc}}</div>
            </div>
            <div class="item">
              <div class="label">单位：</div><div class="label">{{item.zxdw}}</div>
            </div>
          </div>
          <div class="left-part">
            <Button type="primary" @click="onDeleteMedical(item.standardCode)" :disabled="reviewMode">删除药品</Button>
          </div>
        </div>
        <div class="table nfour">
          <Table :columns="reviewMode == true?columns1:columns" border :data="item.drugs">
            <div slot="footer" name="footer" class="tableFooter" v-if="item.drugs.length">
                <div class='nfive' >合计</div>
                <div :class='{nsix:reviewMode == true,nsix1:reviewMode == false}' >{{genTotal(item.drugs, 'purchaseNumber')}}</div>
            </div>
          </Table>
          <div class="footer-my">
            <div class="right-part">
              <div class="item">
                <div class="label">采购单价：</div><div class="label"><InputNumber :max="999999" :disabled="reviewMode" v-model="item.money" :min="0" />元</div>
              </div>
              <div class="item neight" >
                <div class="label">金额：</div><div class="label">{{item.money * genTotal(item.drugs, 'purchaseNumber')}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template v-if="displayDrugGroup.length">
      <div class="footer-my nseven" >
        <div class="right-part">
          <FormItem label="数量总计：" :label-width="120">
              {{genTotalCount()}}
          </FormItem>
          <FormItem label="金额总计：" :label-width="120">
              {{genTotalMoney()}}元
          </FormItem>
          <FormItem label="实付金额：" prop="paidMoney" :label-width="120">
              <InputNumber :disabled="reviewMode" :max="999999" v-model="pageData.paidMoney" :min="0" />元
          </FormItem>
        </div>
      </div>
      <div class="item nnine" >
        <FormItem label="备注:"  prop="remarks" :label-width="80">
          <Input class='nten' :disabled="reviewMode" type="textarea" v-model="pageData.remarks" />
        </FormItem>
      </div>
    </template>
    <div class="btn-group">
      <Button class="btn" type="primary" v-if="!reviewMode" @click="handleSaveOrSubmit(0)">保存</Button>
      <Button class="btn" type="primary" v-if="!reviewMode" @click="handleSaveOrSubmit(1)">提交</Button>
      <Button  class="btn" @click="handleBack">取消</Button>
      <Button  class="btn" type="primary" v-if="reviewMode" @click="handleExport">导出供货清单</Button>
    </div>
    </Form>
    <drugPurchaseModal v-model="showDrugPurchaseModal" :onOk="onOk"/>
  </div>
</template>

<script>
import api from "@/api/commonApi";
import cookie from "@/utils/cookie.js";
import Utils from '@/utils';
import { DatePicker } from "view-design";
import drugPurchaseModal from "./drugPurchaseModal";
export default {
  components: {
    drugPurchaseModal,
    DatePicker
  },
  props: {
    mode: String
  },
  data() {
    const that = this;
    return {
      username: null,
      supplierLinkName: null,
      supplierLinkNumber: null,
      pageData: {
        supplierId: null,
        createTime: Utils.getNowDateBySpecialFormat(new Date()),
        drugs: [],
        paidMoney: null,
        remarks: ''
      },
      displayDrugGroup: [],
      rulePageData: {
        supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
        createTime: [{ required: true, type: 'date', message: '请选择采购日期', trigger: 'change' }],
        paidMoney: [{ required: true, type: 'number', message: '请填写实付金额', trigger: 'change' }],
      },
      supplierList: [],
      showDrugPurchaseModal: false,
      columns: [
        { type: 'index', title: '排序', width: 60, align: 'center' },
        { title: '采购申请单号', key: 'applyNo',},
        { title: '药店', key: 'hospital', },
        { title: '联系人', key: 'linkman',  },
        { title: '联系电话', key: 'linkmanPhone', },
        { title: '申请日期', key: 'applyTime', },
        { title: '采购数量', key: 'purchaseNumber', },
        { title: '操作', key: '_operate', width: 100,render(h, params) {
          const { standardCode, id } = params.row;
          return h('Button', {
            props: {
              type: 'primary'
            },
            on: {
              click() {
                const curItem = that.displayDrugGroup.filter(item => item.standardCode === standardCode)[0];
                curItem.drugs = curItem.drugs.filter(item => item.id !== id);
                if (!curItem.drugs.length) {
                  that.displayDrugGroup = that.displayDrugGroup.filter(item => item.standardCode !== standardCode)
                }
              }
            }
          }, '删除')
        } },
      ],
      columns1: [
        { type: 'index', title: '排序', width: 60, align: 'center' },
        { title: '采购申请单号', key: 'applyNo',},
        { title: '药店', key: 'hospital',},
        { title: '联系人', key: 'linkman', },
        { title: '联系电话', key: 'linkmanPhone', },
        { title: '申请日期', key: 'applyTime',  },
        { title: '采购数量', key: 'purchaseNumber', }
      ]
    }
  },
  created() {
    this.username = cookie.getCookie("userName");
  },
  computed: {
    reviewMode() {
      return this.mode === 'review';
    }
  },
  mounted() {
    this.findPurchaseSupplierListByPage();
  },
  methods: {
    handleBack() {
      const { pagination, filterObj } = this.$route.query;
      this.$router.push({
        path: '/index/drugfirmsmanage/procurement/purchaseOrderMgt/list',
        query: {
          pagination,
          filterObj
        }
      })
    },
    genTotalCount() {
      let resTotal = 0;
      this.displayDrugGroup.forEach(item => {
        item.drugs.forEach(item2 => {
          !!item2 && (resTotal += Number(item2.purchaseNumber));
        })
      });
      return resTotal;
    },
    genTotalMoney() {
      let resTotal = 0;
      this.displayDrugGroup.forEach(item => {
        let totalCount = 0;
        item.drugs.forEach(item2 => {
          !!item2 && (totalCount += Number(item2.purchaseNumber));
        });
        resTotal += (totalCount * Number(item.money));
      });
      return resTotal;
    },
    onDeleteMedical(standardCode) {
      this.displayDrugGroup = this.displayDrugGroup.filter(item => item.standardCode !== standardCode);
    },
    genTotal(drugs ,type) {
      let resTotal = 0;
      drugs.forEach(item => {
        item[type] && (resTotal += Number(item[type]));
      });
      return resTotal;
    },
    onOk(record) {
      this.findPurchaseItemsByDrugId(record.standardCode,record.id);
    },
    handleExport() {
      this.$axios
        .post(api.exportPurchase, {id: this.$route.params.id},
          {
          responseType: 'blob'
        })
        .then(response => {
          if (response.data && response.data.type === 'application/vnd.ms-excel') {
            const fileName = '供货清单.xls';
            const blob = new Blob([response.data], { type: 'application/ms-excel' })
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            // console.log(elink.href)
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
          }
        })
    },
    findPurchaseItemsByDrugId(standardCode,id) {
      this.$axios.post(api.getPurchaseItemsByDrugId, {id:standardCode}).then(res => {
          if (res.data.code === 1) {
              const list = JSON.parse(JSON.stringify(res.data.object || []));
              if (!list.length) {
                this.$Message.info('当前药品无采购信息');
              } else {
                const curItem = this.displayDrugGroup.filter(item => item.standardCode === standardCode)[0];
                if (curItem) {
                  curItem.drugs = list;
                } else {
                  this.displayDrugGroup.push({
                    standardCode: list[0].standardCode,
                    ypmc: list[0].ypmc,
                    ypjx: list[0].ypjx,
                    ypgg: list[0].ypgg,
                    scqymc: list[0].scqymc,
                    zxdw: list[0].zxdw,
                    id: list[0].id,
                    money: 0,
                    drugs: list
                  });
                }
                this.showDrugPurchaseModal = false;
              }
          } else {
              this.$Message.error(res.data.message);
          }
      });
    },
    findPurchaseSupplierListByPage() {
      const reqBody = {
        page: 1,
        row: 9999,
        enable:1,
      };
      this.$axios.post(api.getPurchaseSupplierInfoPage, reqBody).then(res => {
          if (res.data.code === 1) {
              const { records } = res.data.object;
              this.supplierList = records;
              // 反显数据
              if (this.mode !== 'add') {
                this.findPurchaseById();
              }
          } else {
              this.$Message.error(res.data.message);
          }
      });
    },
    handleSaveOrSubmit(type) {
      this.$refs['formHead'].validate((validate) => {
        if (validate) {
          const { supplierId, remarks, paidMoney, createTime, id  } = this.pageData;
          let name
          this.supplierList.forEach((item, index) => {
            if(supplierId==item.id){
              name=item.name
            }
          });
          console.log(name)
          const reqBody = {
            id,
            supplierId,
            supplierName:name,
            paidMoney,
            remarks,
            purchaseTime: Utils.getNowDateBySpecialFormat(createTime),
            drugs: [],
            status: type,
          };
          const reqDrugs = [];
          this.displayDrugGroup.forEach((item, index) => {
            item.drugs.forEach((item2, index2) => {
              item2.sort = index;
              item2.money = item.money;
              reqDrugs.push(item2);
            });
          });
          reqBody.drugs = reqDrugs;
          let message = ''
          this.$axios.post(api.savePurchaseData, reqBody).then(res => {
              if (res.data.code === 1) {
                if(type == 1) {
                  message = '提交成功'
                } else if(type == 0) {
                  message = '保存成功'
                }
                this.$Message.success(message)
                this.handleBack();
              } else {
                  this.$Message.error(res.data.message);
              }
          });
        } else {
          this.$Message.error('有必填项未填写');
        }
      });
    },
    findPurchaseById() { 
      this.$axios.post(api.getPurchaseById, {id: this.$route.params.id}).then(res => {
          if (res.data.code === 1) {
              this.pageData = JSON.parse(JSON.stringify(res.data.object));
              this.pageData.createTime = new Date(this.pageData.createTime);
              this.pageData.paidMoney = this.pageData.purchasePaidMoney;
              delete this.pageData.purchasePaidMoney;
              //
              this.pageData.drugs.forEach(item => {
                const curItem = this.displayDrugGroup.filter(item2 => item2.standardCode === item.standardCode)[0];
                if (curItem) {
                  curItem.drugs.push(item);
                } else {
                  this.displayDrugGroup.push({
                    standardCode: item.standardCode,
                    ypmc: item.ypmc,
                    ypjx: item.ypjx,
                    ypgg: item.ypgg,
                    scqymc: item.scqymc,
                    zxdw: item.zxdw,
                    id: item.id,
                    // 入参入出参不是一个字段 money => purchaseMoney;
                    money: Number(item.purchaseMoney || 0),
                    drugs: [item]
                  });
                }
              });
          } else {
              this.$Message.error(res.data.message);
          }
      });
    },
  },
  watch: {
    'pageData.supplierId'(n) {
      if (n) {
        const curItem = this.supplierList.filter(item => item.id === n)[0];
        this.supplierLinkName = curItem.linkman;
        this.supplierLinkNumber = curItem.linkmanTelephone;
      }
    },
  }
}
</script>

<style scoped lang="less">
.orderNo{
  margin-bottom: 10px; display: flex;
  div{padding-left: 10px}
}
.none{width: 200px;}
.ntwo{width:160px;}
.nthree{margin-bottom: 20px;}
.nfour{margin: 20px 0}
.nfive{width: 61px;}
.nsix{width: 150px;
  margin-right: 20px;
  position: absolute;
  top: 0;
  right: 0;
}
.nsix1{width: 150px;
  margin-right: 20px;
  position: absolute;
  top: 0;
  right: 80px;
}
.nseven{width: 1120px;}
.neight{margin-left: 20px}
.nnine{display: flex; margin: 20px 0;}
.nten{width: 1050px;}
.head-part {
  .des-content {
    display: flex;
    justify-content: space-between;
    .left-part {
      display: flex;
    }
    .right-part {
      display: flex;
    }
  }
}
.btn-group {
  text-align: center;
  .btn {
    width: 100px;
    &:nth-child(2) {
      margin: 0 10px;
    }
  }
}
.medical-block {
  width: 1120px;
  border: 1px solid #ccc;
  padding: 20px 20px 0;
  margin-bottom: 20px;
  .head {
    display: flex;
    justify-content: space-between;
    .left-part {
      display: flex;
      .item {
        display: flex;
        margin-right: 20px;
      }
    }
  }
}
.table-part {
  .tableFooter {
      display: flex;
      position: relative;
    &>div {
      border-right: 1px solid #e9eaec;
      padding: 0 18px;
      &:last-child {
        border: none;
      }
    }
  }
}
.footer-my {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
  .right-part {
    display: flex;
    .item {
      display: flex;
      align-items: center;
    }
  }
}
</style>